package com.cloud.poetry.base.databases;

import com.cloud.poetry.core.constant.DataSourceEnum;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @author mengxj
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    private static ThreadLocal<DataSourceEnum> context = new ThreadLocal<>();

    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    public static void setDataSource(DataSourceEnum dataSource){
        context.set(dataSource);
    }

    public static void clearDataSource(){
        context.remove();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return context.get();
    }
}
